package com.csw.android.developutils.test.app_utils

import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.csw.android.dev_utils.ex.JsonEx.toJsonString
import com.csw.android.dev_utils.log.LogDisplayController
import com.csw.android.dev_utils.log.request.RequestLogInfo
import com.csw.android.dev_utils.ui.CommonOpen
import com.csw.android.dev_utils.ui.FragmentViewProperty
import com.csw.android.dev_utils.ui.databinding.DataBindingFragment
import com.csw.android.dev_utils.utils.CommonBluetoothScanListener
import com.csw.android.dev_utils.utils.LogUtils
import com.csw.android.developutils.R
import com.csw.android.developutils.databinding.UiTestCommonOpenBinding
import com.tbruyelle.rxpermissions3.RxPermissions
import java.util.regex.Pattern

class AActivity : AppCompatActivity() {

    private val bluetoothScanListener = object : CommonBluetoothScanListener() {

        override fun onScanStarted(success: Boolean) {
            super.onScanStarted(success)
            LogUtils.e(this@AActivity,"BLE:onScanStarted ${success}")
        }

        @SuppressLint("MissingPermission")
        override fun onScanning(bleDevice: BleDevice) {
            super.onScanning(bleDevice)
            LogUtils.e(this@AActivity,"BLE:onScanning${bleDevice.device.name}")
        }

        override fun onScanFinished() {
            super.onScanFinished()
            LogUtils.e(this@AActivity,"BLE:onScanFinished")
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(View(this).apply {
            setBackgroundColor(Color.RED)
            setOnClickListener {
//                startActivity(Intent(this@AActivity, BActivity::class.java))
                DFragment.open(it.context)
            }
        })
        LogDisplayController.instance.addLog(RequestLogInfo(
            Log.WARN, System.currentTimeMillis(), packageName, "Test"
        ).apply {
            request.value = hashMapOf<String, Any>("1" to 1, "2" to "B").toJsonString()
            requestHeader.value = hashMapOf("head1" to "__1__", "head2" to "__2__").toJsonString()
            response.value = hashMapOf<String, Any>("response" to "_____").toJsonString()
        })

        val permissions = ArrayList<String>()
        permissions.add(Manifest.permission.BLUETOOTH)
        permissions.add(Manifest.permission.BLUETOOTH_ADMIN)
        permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION)
        permissions.add(Manifest.permission.ACCESS_FINE_LOCATION)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            permissions.add(Manifest.permission.BLUETOOTH_SCAN)
            permissions.add(Manifest.permission.BLUETOOTH_CONNECT)
        }
        RxPermissions(this).request(
            *(permissions.toTypedArray())
        ).subscribe{
           if(it){
               bluetoothScanListener.lifecycleOwner = this
               bluetoothScanListener.scanDuration = 10 * 1000
               bluetoothScanListener.deviceNamePattern = Pattern.compile(
                   ".*Smart-.*|.*SDMC-.*"
               )
           }
        }
    }

}

class BActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(View(this).apply {
            setBackgroundColor(Color.GREEN)
            setOnClickListener {
                startActivity(Intent(this@BActivity, CActivity::class.java))
            }
        })
    }

}

class CActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(View(this).apply {
            setBackgroundColor(Color.GREEN)
            setOnClickListener {
                AlertDialog.Builder(it.context).setTitle("测试")
                    .setMessage("对话框对生命周期的影响").show()
            }
        })
    }

}

class DFragment : DataBindingFragment<UiTestCommonOpenBinding>() {

    companion object : CommonOpen

    private var desc: String? by FragmentViewProperty {
        LogUtils.d(this, "属性回收，当前值${it.toString()}")
    }

    private val bluetoothScanListener = object : CommonBluetoothScanListener() {

        override fun onScanStarted(success: Boolean) {
            super.onScanStarted(success)
            LogUtils.e(this@DFragment,"BLE:onScanStarted ${success}")
        }

        @SuppressLint("MissingPermission")
        override fun onScanning(bleDevice: BleDevice) {
            super.onScanning(bleDevice)
            LogUtils.e(this@DFragment,"BLE:onScanning${bleDevice.device.name}")
        }

        override fun onScanFinished() {
            super.onScanFinished()
            LogUtils.e(this@DFragment,"BLE:onScanFinished")
        }

    }

    override fun getContentViewID() = R.layout.ui_test_common_open

    override fun initView(rootView: View, savedInstanceState: Bundle?) {
        super.initView(rootView, savedInstanceState)
        desc = "Test common open."
        dataBinding?.desc?.text = desc
    }

    override fun initListener() {
        super.initListener()

        val permissions = ArrayList<String>()
        permissions.add(Manifest.permission.BLUETOOTH)
        permissions.add(Manifest.permission.BLUETOOTH_ADMIN)
        permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION)
        permissions.add(Manifest.permission.ACCESS_FINE_LOCATION)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            permissions.add(Manifest.permission.BLUETOOTH_SCAN)
            permissions.add(Manifest.permission.BLUETOOTH_CONNECT)
        }
        RxPermissions(this).request(
            *(permissions.toTypedArray())
        ).subscribe{
            if(it){
                bluetoothScanListener.lifecycleOwner = this
                bluetoothScanListener.scanDuration = 1 * 1000
                bluetoothScanListener.deviceNamePattern = Pattern.compile(
                    ".*Smart-.*|.*SDMC-.*"
                )
            }
        }
    }
}